package com.tovast.demo.controller;

import com.tovast.demo.domain.User;
import com.tovast.demo.repository.UserRepostiroy;
import com.tovast.demo.service.SecurityMangeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by zjp on 2016/9/24.
 */
@Controller
@RequestMapping("user")
public class HelloWordController {
    @Autowired
    private SecurityMangeService securityMangeService;
    @Autowired
    private UserRepostiroy userRepostiroy;
    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public Page< User> list(@RequestParam("name") String name, Pageable pageable){

       return  userRepostiroy.findAllByNameContaining(name,pageable);
    }
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public User registe(@RequestBody User user){

        securityMangeService.registe(user);
        return user;
    }
    @RequestMapping(value = "{id}" ,method = RequestMethod.GET)
    @ResponseBody
    public User findOne(@PathVariable("id") int id){

        return userRepostiroy.findOne(id);
    }
    @RequestMapping(value = "{id}" ,method = RequestMethod.DELETE)
    @ResponseBody
    public User delete(@PathVariable("id") int id){
       User user= userRepostiroy.findOne(id);
        securityMangeService.destroy(user);
        return user;
    }
    @RequestMapping(value = "{id}" ,method = RequestMethod.PUT)
    @ResponseBody
    public User update(@PathVariable("id") int id, @RequestBody User user){
        User old=userRepostiroy.findOne(id);
        old.setName(user.getName());
        userRepostiroy.saveAndFlush(old);
        return user;
    }
}
